package modules.ulock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 锁的理解
 *   死锁
 *   排查死锁：
 *      1 使用jps定位进程号，jdk的bin目录下： 有一个jps  命令：jps -l
 *      2 使用`jstack` 进程进程号 找到死锁信息  命令：jstack  进程号
 * @author shengren.yan
 * @create 2021-04-16
 */
public class ULock3 {
    // 出现死锁
    public static void main(String[] args) throws Exception {
        String lockA= "lockA";
        String lockB= "lockB";

        new Thread(new MyThread(lockA,lockB),"t1").start();
        new Thread(new MyThread(lockB,lockA),"t2").start();
    }
}

class MyThread implements Runnable{

    private String lockA;
    private String lockB;

    public MyThread(String lockA, String lockB) {
        this.lockA = lockA;
        this.lockB = lockB;
    }

    @Override
    public void run() {
        synchronized (lockA){
            System.out.println(Thread.currentThread().getName()+" lock"+lockA+"===>get"+lockB);
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (lockB){
                System.out.println(Thread.currentThread().getName()+" lock"+lockB+"===>get"+lockA);
            }
        }
    }
}
